package com.bigknow.appstore.proxy.handler.lock;

import com.bigknow.appstore.proxy.util.HandlerVariables;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;

import java.util.concurrent.ArrayBlockingQueue;

/**
 * 添加闭锁
 * Created by chaos on 2016/9/13.
 */
@ChannelHandler.Sharable
public class AddAckHandler extends ChannelInboundHandlerAdapter {

    public AddAckHandler() {
    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        HandlerVariables.acks.put(ctx.channel().id().asLongText(), new ArrayBlockingQueue(1));
        ctx.fireChannelActive();
    }

    @Override
    public void channelRegistered(ChannelHandlerContext ctx) throws Exception {
        HandlerVariables.acks.put(ctx.channel().id().asLongText(), new ArrayBlockingQueue(1));
        ctx.fireChannelRegistered();
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        ArrayBlockingQueue queue = HandlerVariables.acks.get(ctx.channel().id().asLongText());
        queue.put(1);//如果队列满了就么法在放进去，这个时候就会等待
        ctx.fireChannelRead(msg);
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        clearAck(ctx.channel().id().asLongText());
        ctx.fireChannelInactive();
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause)
            throws Exception {
        clearAck(ctx.channel().id().asLongText());
        ctx.fireExceptionCaught(cause);
    }

    private void clearAck(String channelId) {
        ArrayBlockingQueue queue = HandlerVariables.acks.remove(channelId);
        if (queue != null) queue.clear();
    }
}
